<?php

/**
 * The base model from which all project models inherit.
 */
class BlogBaseModel extends AgaviModel
{
    /**
     * Maximum number of mkdir attempts when creating directories.
     *
     */
    const MAX_MKDIR_TRIES = 30;
    const MAX_MKFILE_TRIES = 30;
    
    /**
     * Retrieve PDO object required to access to the blog database
     *
     * @return PropelPDO
     */
    protected function getPdo()
    {
        return $this->getContext()->getDatabaseManager()->getDatabase('blog')->getConnection();
    }
    
    /**
     * Create directory with random name in the specified directory.
     *
     * @param string $dir
     * @param string $prefix
     * @param integer $mode 
     * @return string Name of just created directory without path
     * @throws WereWordFilesystemException
     */
    public static function makeRandomDir($dir, $prefix, $mode=0700)
    {
        if (substr($dir, -1) != DIRECTORY_SEPARATOR) { 
            $dir .= DIRECTORY_SEPARATOR;
        }
        
        $n = 0;
        do {
            $dirname = $prefix.mt_rand(0, 9999999);
            $path = $dir . $dirname;
            $n += 1;
            if ($n > self::MAX_MKDIR_TRIES) {
                break;
            }
        } while (!mkdir($path, $mode));
        
        // check that $path exists and is directory
        if (!is_dir($path)) {
            throw new WereWordFilesystemException('Unable to create directory within provided path, '.
                'check permissions for the directory '.$dir);
        }
        
        return $dirname;
    }
    
    /**
     * Create file with random name in the specified directory
     *
     * @param string $dir
     * @param string $prefix
     * @param string $mode
     * @return string Name of just created file without path
     */
    public static function makeRandomFile($dir, $prefix, $mode='w')
    {
        if (substr($dir, -1) != DIRECTORY_SEPARATOR) { 
            $dir .= DIRECTORY_SEPARATOR;
        }
        
        $n = 0;
        $fh = FALSE;
        do {
            $filename = $prefix.mt_rand(0, 9999999);
            $path = $dir . $filename;
            $n += 1;
            if ($n > self::MAX_MKFILE_TRIES) {
                break;
            }
        } while (file_exists($path) || FALSE===($fh=fopen($path, $mode)));
        // stop when (file doesn't exists && file created)
        
        // check that $path was created
        if (FALSE === $fh) {
            throw new WereWordFilesystemException('Unable to create file within provided path, '.
                'check permissions for the directory '.$dir);
        }
        
        return $filename;
    }
}

?>